import { OneModal } from '@/components/one-ui';
import { ContractManageAPI } from '../common/type';
import { IOneModalRef } from '@/pages/type';
import { Ref, useEffect, useMemo, useRef, useState } from 'react';
import { Col, Form, Row, Spin, DatePicker, message, InputNumber, Tooltip } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import { UploadFormCommon } from '@/components/UploadForm';
import { getTenantID, onCloseModalCommon } from '@/utils';
import { getMcontractByIDService, signContractService } from '../services';
import moment from 'moment';
import { ILoadMapTypeAll } from '@/common';
import { QuestionCircleOutlined } from '@ant-design/icons';

const TodayDatePicker: any = DatePicker;

export const ContractSignModal: React.FC<ContractManageAPI.IContractSignModal> = ({ onClose, selectRowInfo, reloadManage }) => {
  /** 弹框ref */
  const singModalRef: Ref<IOneModalRef> = useRef(null);

  /** 表单form */
  const [singFrom] = Form.useForm();

  /** 保存时间 */
  const [realBeginTimeStart, setRealBeginTimeStart] = useState<any>();

  /** 保存数据 */
  const [detailInfoObj, setDetailInfoObj] = useState<Record<string, any>>({});

  /** 保存回调 */
  const onSingCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
      onCloseModalCommon(singModalRef);
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入接口 */
  const { signContractLoading, signContractRun } = signContractService(onSingCallback);

  /** 详情接口回调 */
  const detailCallback = (res: any) => {
    if (res && res?.msgFlag) {
      setDetailInfoObj({
        ...res?.obj,
        paramObject: {
          mactivitiHisTaskInstList:
            res?.obj?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList,
        },
      });
    } else {
      message.error(res?.msg);
    }
  };

  // /** 引入详情接口 */
  const { getMcontractByIDLoading, getMcontractByIDRun } = getMcontractByIDService(detailCallback);

  useEffect(() => {
    if (selectRowInfo && selectRowInfo?.id) {
      getMcontractByIDRun({
        id: selectRowInfo?.id,
      });
    }
  }, [selectRowInfo]);

  /** 保存 */
  const onSave = () => {
    singFrom?.validateFields()?.then((values: any) => {
      let list = { ...detailInfoObj };
      if (list?.paramObject && list?.paramObject?.mactivitiHisTaskInstList && list?.paramObject?.mactivitiHisTaskInstList?.length) {
        list.paramObject.mactivitiHisTaskInstList = list?.paramObject?.mactivitiHisTaskInstList?.filter((item) => item?.assigneeID) || [];
      }
      const payload: Record<string, any> = {
        // ...selectRowInfo,
        ...list,
        ...values,
        realBeginTime: values?.realBeginTime ? moment(values?.realBeginTime)?.format('YYYY-MM-DD HH:mm:ss') : selectRowInfo?.realBeginTime,
        realFinishTime: values?.realFinishTime ? moment(values?.realFinishTime)?.format('YYYY-MM-DD HH:mm:ss') : selectRowInfo?.realFinishTime,
        id: selectRowInfo?.id,
        pID: selectRowInfo?.pID,
        changeWay: selectRowInfo?.changeWay,
        changeFlag: selectRowInfo?.changeFlag,
        state:
          selectRowInfo?.changeWay == 1 ? `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1006` : `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1004`,
        pState:
          selectRowInfo?.changeWay == 1 ? `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1006` : `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1004`,
        versionNum: selectRowInfo?.versionNum,
      };

      signContractRun(payload);
    });
  };

  /** 判断是否显示实际时间 */
  const showRealTimeMemo = useMemo(() => {
    if (selectRowInfo?.changeWay == 0 || selectRowInfo?.changeWay == 1) {
      if (selectRowInfo?.changeTerm == 1) {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  }, [selectRowInfo]);

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={singModalRef}
      title={'上传扫描件'}
      onCancel={onClose}
      width={document.body.clientWidth * 0.25}
      bodyStyle={{ padding: 0 }}
      confirmLoading={signContractLoading || getMcontractByIDLoading}
      onOk={onSave}
    >
      <Spin spinning={signContractLoading || getMcontractByIDLoading}>
        <div className={pageStyles['fromView-styles']}>
          <Form form={singFrom}>
            <Row>
              <UploadFormCommon
                form={singFrom}
                label="合同扫描件"
                fileFormName={'scanURL'}
                spanCol={24}
                inRowProportion={24}
                name={'attachFile'}
                required={true}
                accept={'.pdf'}
                url={'/contractController/uploadFile'}
                downloadUrl={'/contractController/downloadFile'}
                fileFormDelName={'scanURLDel'}
                delFunc={() => {}}
                maxFile={1}
                defaultFiles={null}
                fieldBusiPath={'contract/scan'}
              >
                合同扫描件
              </UploadFormCommon>

              {/* 判断是否显示时间,变更解除未选择修改履约期限 */}
              {showRealTimeMemo && (
                <>
                  <Col span={24}>
                    <Form.Item
                      name="periodNum"
                      label={
                        <>
                          质保期&nbsp;
                          <Tooltip title="若无质保期请填写 0">
                            <a>
                              <QuestionCircleOutlined />
                            </a>
                          </Tooltip>
                        </>
                      }
                      rules={[
                        {
                          required: true,
                          message: '若无质保期请填写 0',
                        },
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!getFieldValue('realBeginTime') || !getFieldValue('realFinishTime')) {
                              return Promise.resolve();
                            }
                            if (value == 0 || value == null) {
                              return Promise.resolve();
                            }
                            if (value > moment(getFieldValue('realFinishTime')).diff(moment(getFieldValue('realBeginTime')), 'months')) {
                              return Promise.reject(new Error('签订截止时间减签订开始时间得到的月份应大于等于质保期。'));
                            }
                            return Promise.resolve();
                          },
                        }),
                      ]}
                      dependencies={['realBeginTime', 'realFinishTime']}
                    >
                      <InputNumber placeholder="请输入质保期" addonAfter="月" />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      name="realBeginTime"
                      label="合同签订时间"
                      rules={[
                        {
                          required: true,
                          message: '请选择合同签订时间',
                        },
                      ]}
                      dependencies={['periodNum', 'realFinishTime']}
                    >
                      <TodayDatePicker
                        placeholder="请选择合同签订时间"
                        style={{ width: '100%' }}
                        format="YYYY-MM-DD"
                        onChange={(date: any) => {
                          setRealBeginTimeStart(date);
                        }}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      name="realFinishTime"
                      label="合同截止时间"
                      rules={[
                        {
                          required: true,
                          message: '请选择合同截止时间',
                        },
                      ]}
                      dependencies={['periodNum', 'realBeginTime']}
                    >
                      <TodayDatePicker
                        placeholder="请选择合同截止时间"
                        style={{ width: '100%' }}
                        format="YYYY-MM-DD"
                        disabledDate={(date: any) => {
                          const currentDate: any = realBeginTimeStart ? realBeginTimeStart : date;
                          return date && date < currentDate;
                        }}
                      />
                    </Form.Item>
                  </Col>
                </>
              )}
            </Row>
          </Form>
        </div>
      </Spin>
    </OneModal>
  );
};
